package patrol.mobile.com.mobilepatrol.activity.toll.add_data;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.VideoPlayActivity;
import patrol.mobile.com.mobilepatrol.activity.office.AdviceDetailActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.bean.OrgPostTemplateListBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.picker.matisse.Matisse;
import patrol.mobile.com.mobilepatrol.picker.matisse.MimeType;
import patrol.mobile.com.mobilepatrol.picker.matisse.engine.GlideEngine;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

public class AddDataPage3Activity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.tv_koufen)
    TextView tvKoufen;
    @BindView(R.id.tv_advice)
    EditText tvAdvice;
    @BindView(R.id.tv_koufen_biaozhun)
    TextView tvKoufenBiaozhun;
    @BindView(R.id.btn_per)
    Button btnPer;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_total)
    TextView tv_total;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    private int limitSize = 4;
    private OrgPostTemplateListBean bean;
    private int currentPosition;
    //    private int score=0;
    private String videoPath = "";
    public static final int REQUEST_CODE_VSELECT = 102;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_evaluation_content;
    }

    @Override
    public void initView() {
        super.initView();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        comiitPageData();
                        Intent intent = new Intent();
                        intent.putExtra("data", bean);
//                        intent.putExtra("score", score);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("考核内容");
    }

    @Override
    public void onBackPressed() {
        comiitPageData();
        Intent intent = new Intent();
        intent.putExtra("data", bean);
//        intent.putExtra("score", score);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }


    @Override
    public void initData() {
        super.initData();
        bean = (OrgPostTemplateListBean) getIntent().getSerializableExtra("data");
        currentPosition = getIntent().getIntExtra("position", 0);
        if (bean == null) return;
        tvTitle.setText((currentPosition + 1) + "." + bean.getList().get(currentPosition).getProSmall());
        tvKoufen.setText(bean.getList().get(currentPosition).getAccount() + "");
        tv_total.setText(bean.getList().get(currentPosition).getItemScore() + "");
        tvAdvice.setText(bean.getList().get(currentPosition).getReason());
        tv_content.setText(bean.getList().get(currentPosition).getProContent());
        tvKoufenBiaozhun.setText(bean.getList().get(currentPosition).getGradingStandard());
        for (int i = 0; i < bean.getList().size(); i++) {
            bean.getList().get(i).setAuditFlag("1");
            bean.getList().get(i).setId(i + System.currentTimeMillis() + UserManager.getUserId());
        }
        setImageSelectData();
    }

    /**
     * 设置图片选择数据
     */
    private void setImageSelectData() {
        initImagePicker();
        selImageList = bean.getList().get(currentPosition).getSelImageList();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void setListener() {
        btnPer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                comiitPageData();
                currentPosition--;
                if (currentPosition < 0) {
                    showToast("没有上一项");
                    currentPosition = 0;
                    return;
                }
                List<OrgPostTemplateListBean.ListBean> orgPostItemList = bean.getList();
                tvTitle.setText((currentPosition + 1) + "." + orgPostItemList.get(currentPosition).getProSmall());
                tvKoufen.setText(orgPostItemList.get(currentPosition).getAccount() + "");
//                score=orgPostItemList.get(currentPosition).getAccount();
                tv_total.setText(bean.getList().get(currentPosition).getItemScore() + "");
                tvAdvice.setText(orgPostItemList.get(currentPosition).getReason());
                tv_content.setText(bean.getList().get(currentPosition).getProContent());
                tvKoufenBiaozhun.setText(orgPostItemList.get(currentPosition).getGradingStandard());
                setImageSelectData();
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                comiitPageData();
                currentPosition++;
                List<OrgPostTemplateListBean.ListBean> orgPostItemList = bean.getList();
                if (currentPosition > orgPostItemList.size() - 1) {
                    showToast("没有下一项");
                    currentPosition = orgPostItemList.size() - 1;
                    return;
                }
                tvTitle.setText((currentPosition + 1) + "." + orgPostItemList.get(currentPosition).getProSmall());
                tvKoufen.setText(orgPostItemList.get(currentPosition).getAccount() + "");
                tv_total.setText(bean.getList().get(currentPosition).getItemScore() + "");
                tv_content.setText(bean.getList().get(currentPosition).getProContent());
                tvAdvice.setText(orgPostItemList.get(currentPosition).getReason());
                tvKoufenBiaozhun.setText(orgPostItemList.get(currentPosition).getGradingStandard());
                setImageSelectData();
            }
        });
    }

    /**
     * 切换页数前保存当前页面数据
     */
    private void comiitPageData() {
//        score+=Integer.parseInt(tvKoufen.getText().toString());
        int score = Integer.parseInt(tvKoufen.getText().toString());
        int standarScore = bean.getList().get(currentPosition).getItemScore();
        bean.getList().get(currentPosition).setAccount(score > standarScore ? standarScore : score);
        bean.getList().get(currentPosition).setReason(tvAdvice.getText().toString());
        bean.getList().get(currentPosition).setGradingStandard(tvKoufenBiaozhun.getText().toString());
        bean.getList().get(currentPosition).setSelImageList(selImageList);
        bean.getList().get(currentPosition).setIsNewRecord(true);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case AdviceDetailActivity.IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                names.add("视频");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(view.getContext(), ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(view.getContext(), ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 2:
//                                Intent i = new Intent();
//                                i.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
//                                i.setAction(Intent.ACTION_GET_CONTENT);
//                                startActivityForResult(i, REQUEST_CODE_VSELECT);
                                Matisse.from(AddDataPage3Activity.this)
                                        .choose(MimeType.ofVideo())
                                        .showSingleMediaType(true)
                                        .theme(R.style.Matisse_Dracula)
                                        .countable(false)
                                        .maxSelectable(1)
                                        .imageEngine(new GlideEngine())
                                        .forResult(REQUEST_CODE_VSELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(view.getContext(), ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(view.getContext(), ImageGridActivity.class);
                                startActivityForResult(intent1, AdviceDetailActivity.REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                //打开预览
                if (adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, AdviceDetailActivity.REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, AdviceDetailActivity.REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            for (int i = 0; i < images.size(); i++) {
                                images.get(i).mimeType = "image";
                            }
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case RESULT_OK:
                    //选择视频返回
                    if (requestCode == REQUEST_CODE_VSELECT) {
                        List<String> videoUrls = Matisse.obtainPathResult(data);
                        Log.e("videoUrls", videoUrls.get(0));
                        videoPath = videoUrls.get(0);
                        MediaMetadataRetriever retr = new MediaMetadataRetriever();
                        retr.setDataSource(videoPath);
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = retr.getFrameAtTime();
                        String imgUrl = FileUtil.saveImg2Gallery(this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = imgUrl;
                        imageItem.name = videoPath;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        adapter.setImages(selImageList);

                    }
                    break;
            }
        }
//        if (data != null) {
//            switch (resultCode) {
//                case ImagePicker.RESULT_CODE_ITEMS:
//                    //添加图片返回
//                    ArrayList<ImageItem> images;
//                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_SELECT) {
//                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                        if (images != null) {
//                            selImageList.addAll(images);
//                            adapter.setImages(selImageList);
//                        }
//                    }
//                    break;
//                case ImagePicker.RESULT_CODE_BACK:
//                    //预览图片返回
//                    if (requestCode == AdviceDetailActivity.REQUEST_CODE_PREVIEW) {
//                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
//                        if (images != null) {
//                            selImageList.clear();
//                            selImageList.addAll(images);
//                            adapter.setImages(selImageList);
//                        }
//                    }
//                    break;
//            }
//        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
}
